namespace HZY.Framework.DependencyInjection.Attributes;

/// <summary>
/// 配置文件属性注入 配置文件中 value 如果是 $(xxxKey) 这种格式 ，那么自动去读取环境变量
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class ValueAttribute(string key) : AopMoAttribute
{
    /// <summary>
    /// 配置节点地址地址
    /// </summary>
    private string Key { get; } = key;

    public override void OnSuccess(MethodContext context)
    {
        if (context.ReturnType == null)
        {
            Debug.WriteLine("Method has no return type.");
            return;
        }

        if (string.IsNullOrWhiteSpace(Key))
        {
            Debug.WriteLine("Configuration key is null or whitespace.");
            return;
        }

        var name = context.Method.Name;
        if (!name.StartsWith("get_"))
        {
            Debug.WriteLine("Method is not a getter.");
            return;
        }

        name = name.Replace("get_", "");

        var configuration = AopMoAttribute.WebApplicationBuilder?.Configuration ??
                            this.GetService<IConfiguration>(context)
            ;

        // 读取 configuration
        var result = configuration?.GetSection(Key).Get(context.ReturnType);

        if (result is null)
        {
            Debug.WriteLine($"Configuration value for key '{Key}' is null.");
            return;
        }

        if (result is string envKeyString)
        {
            // 判断获取的值 是否是这样的 $(xxxKey) 那么是读取环境变量
            if ((envKeyString.StartsWith("$(") && envKeyString.EndsWith($")")) ||
                (envKeyString.StartsWith("${") && envKeyString.EndsWith(new StringBuilder().Append('}').ToString())))
            {
                var envKey = envKeyString.Replace("$(", "");
                envKey = envKey.Replace(")", "");
                envKey = envKey.Replace("${", "");
                envKey = envKey.Replace("}", "");

                result = Environment.GetEnvironmentVariable(envKey);
                if (result is null)
                {
                    Debug.WriteLine($"Environment variable for key '{envKey}' is null.");
                }
            }
        }

        if (result is null)
        {
            Debug.WriteLine("Final result is null after processing.");
            return;
        }

        context.ReplaceReturnValue(this, result);
    }
}